package com.weixin.service.Impl;

import java.util.List;
import java.util.Optional;

import javax.annotation.Resource;

import com.weixin.dao.ProductInfoMapper;
import com.weixin.enums.StatusEnum;
import com.weixin.pojo.ProductInfo;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.weixin.dto.CartDto;
import com.weixin.enums.ResultEnum;
import com.weixin.exception.SellException;
import com.weixin.service.ProductInfoService;

/**
 * 商品表
 * 
 * @author Code generator by CJunGod
 *
 */
@Service
@Transactional
public class ProductInfoServiceImpl implements ProductInfoService {
	
	@Resource
	private ProductInfoMapper productInfoMapper;

	@Override
	public ProductInfo findById(String productId) {
		Optional<ProductInfo> findById = productInfoMapper.findById(productId);
		ProductInfo info = null;
		if(findById.isPresent()) {
			info = findById.get();
		}
		return info;
	}

	@Override
	public List<ProductInfo> findUpAll() {
		
		return productInfoMapper.findByProductStatus(StatusEnum.UP.getCode());
	}

	@Override
	public Page<ProductInfo> findAll(Pageable pageable) {
		
		return productInfoMapper.findAll(pageable);
	}

	@Override
	public ProductInfo save(ProductInfo productInfo) {
		
		return productInfoMapper.save(productInfo);
	}

	@Override
	public void increaseStock(List<CartDto> cartDtos) {
		// TODO Auto-generated method stub
		cartDtos.forEach(c -> {
			Optional<ProductInfo> byId = productInfoMapper.findById(c.getProductId());
			if(byId.isPresent()){
				Integer result = byId.get().getProductStock() + c.getProductQuantity();
				byId.get().setProductStock(result);

				productInfoMapper.save(byId.get());
			}else{
				throw new SellException(ResultEnum.PRODUCT_NOT_EXIST);
			}
		});
	}

	@Override
	public void decreaseStock(List<CartDto> cartDtos) {
		cartDtos.forEach(cart -> {
			Optional<ProductInfo> findById = productInfoMapper.findById(cart.getProductId());
			if(findById.isPresent()) {
				ProductInfo productInfo = findById.get();
				Integer result = productInfo.getProductStock() - cart.getProductQuantity();
				if(result < 0) {
					throw new SellException(ResultEnum.PRODUCT_STOCK_ERROR);
				}
				
				productInfo.setProductStock(result);
				productInfoMapper.save(productInfo);
			}else {
				throw new SellException(ResultEnum.PRODUCT_NOT_EXIST);
			}
			
		});
		
	}

}
